import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { memberService } from '../../api/services/memberService';
import type {
  Member as ApiMember,
  CreateMemberRequest as ApiCreateMemberRequest,
  UpdateMemberRequest as ApiUpdateMemberRequest
} from '../../api/types/member';

export interface Member {
  id: number;
  name: string;
  email?: string;
  phone?: string;
  department?: string;
  status: 'active' | 'inactive';
}

export interface CreateMemberRequest {
  name: string;
  email?: string;
  phone?: string;
  department?: string;
  status?: 'active' | 'inactive';
}

export interface UpdateMemberRequest {
  id: number;
  name?: string;
  email?: string;
  phone?: string;
  department?: string;
  status?: 'active' | 'inactive';
}

interface MemberState {
  members: Member[];
  loading: boolean;
  error: string | null;
}

const initialState: MemberState = {
  members: [],
  loading: false,
  error: null,
};

// 异步 thunks
export const fetchMembers = createAsyncThunk(
  'member/fetchMembers',
  async (_, { rejectWithValue }) => {
    try {
      const response = await memberService.getMembers();
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || error.message || '获取人员列表失败');
    }
  }
);

export const createMember = createAsyncThunk(
  'member/createMember',
  async (memberData: CreateMemberRequest, { rejectWithValue }) => {
    try {
      const response = await memberService.createMember(memberData);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || error.message || '创建人员失败');
    }
  }
);

export const updateMember = createAsyncThunk(
  'member/updateMember',
  async (memberData: UpdateMemberRequest, { rejectWithValue }) => {
    try {
      const { id, ...updateData } = memberData;
      const response = await memberService.updateMember(id, updateData);
      return response;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || error.message || '更新人员失败');
    }
  }
);

export const deleteMember = createAsyncThunk(
  'member/deleteMember',
  async (memberId: number, { rejectWithValue }) => {
    try {
      await memberService.deleteMember(memberId);
      return memberId;
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.message || error.message || '删除人员失败');
    }
  }
);

const memberSlice = createSlice({
  name: 'member',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchMembers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchMembers.fulfilled, (state, action) => {
        state.loading = false;
        state.members = action.payload;
      })
      .addCase(fetchMembers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(createMember.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createMember.fulfilled, (state, action) => {
        state.loading = false;
        state.members.push(action.payload);
      })
      .addCase(createMember.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(updateMember.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(updateMember.fulfilled, (state, action) => {
        state.loading = false;
        const index = state.members.findIndex(m => m.id === action.payload.id);
        if (index !== -1) {
          state.members[index] = action.payload;
        }
      })
      .addCase(updateMember.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(deleteMember.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(deleteMember.fulfilled, (state, action) => {
        state.loading = false;
        state.members = state.members.filter(m => m.id !== action.payload);
      })
      .addCase(deleteMember.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { clearError } = memberSlice.actions;
export default memberSlice.reducer;